package com.study.rabbitmq.demo;

import com.rabbitmq.client.*;
import com.study.rabbitmq.utils.RabbitMqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 消息接收者
 */
public class Consume {
    //队列名
    public static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.99.149.102");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel1 = connection.createChannel();
        DeliverCallback deliverCallback = (comsumeTag,message)->{
            System.out.println(new String(message.getBody(), StandardCharsets.UTF_8));
        };
        CancelCallback cancelCallback;
        channel1.basicConsume(QUEUE_NAME,deliverCallback,cancelCallback=(consumeTag)->{});
        //        //创建连接工厂
//        ConnectionFactory factory = new ConnectionFactory();
//        //设置用户名密码ip端口
//        factory.setUsername("admin");
//        factory.setPassword("123456");
//        factory.setHost("192.168.56.11");
//        factory.setPort(5672);
//        //创建连接
//        Connection connection = factory.newConnection();
//        //创建信道
//        Channel channel = connection.createChannel();

        Channel channel = RabbitMqUtil.getChannel();

        //消息接收的回调函数
        //(1).使用匿名内部类的方法定义回调函数
       /* DeliverCallback deliver = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                System.out.println(delivery);
            }
        };*/
        //(2).使用lamda表达式
        DeliverCallback deliver = (consumerTag,message) -> {
            //只获取消息体
            System.out.println(new String(message.getBody()));
        };

        //消费者取消消息接收的回调方法
        CancelCallback cancel = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {
                System.out.println("消息接收被中断");
            }
        };

        /**
         * 接收消息
         * 参数含义：
         * 1.队列名
         * 2.是否自动应答 true代表自动应答 false代表不自动应答
         * 3.消息接收成功调用的回调函数
         * 4.取消消息接收的回调函数
         */
        channel.basicConsume(QUEUE_NAME,true,deliver,cancel);

    }
}
